const OSS = require('ali-oss')
// import OSS from 'ali-oss'
const uploadHost= 'https://cdzt-media.oss-cn-chengdu.aliyuncs.com'


function random_string(len) {
  len = len || 32
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  var maxPos = chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

function uploadOSS(file, OSSConfig) {
  // console.log('file',file)
  //1、js
  return new Promise(async (resolve, reject) => {
    const fileName = `${random_string(6)}_${file.name}`
    let client = new OSS({
      region: 'oss-'+OSSConfig.region,
      accessKeyId: OSSConfig.accessKeyId,
      accessKeySecret: OSSConfig.accessKeySecret,
      bucket: 'cdzt-media',
      stsToken: OSSConfig.token,
      useFetch: true, // 支持上传大于100KB的文件
      secure:true
    })
    const res = await client.put(fileName, file)
    // console.log('res',res)
    // resolve(res)
    // 或者返回如下：
    resolve({
        fileUrl: `${OSSConfig.uploadHost}/${fileName}`,
        fileName: file.name,
        url: res.url
    })
  })
  let client = new OSS({
      region: 'oss-'+OSSConfig.region,
      accessKeyId: OSSConfig.accessKeyId,
      accessKeySecret: OSSConfig.accessKeySecret,
      bucket: 'cdzt-media',
      stsToken: OSSConfig.token,
      useFetch: true, // 支持上传大于100KB的文件
      // secure:true
    })
    return client.put('obj', new OSS.Buffer('hello world'));
    client.list().then((result) => {
    console.log('objects: %j', result.objects);
    
  }).then((result) => {
    console.log('put result: %j', result);
    return client.get('my-obj');
  }).then((result) => {
    console.log('get result: %j', result.content.toString());
  });

  return false
  return new Promise(async (resolve, reject) => {
    const fileName = `${random_string(6)}_${file.name}`
    console.log('fileName', fileName, uploadHost)
    let client = new OSS({
      region: OSSConfig.region,
      accessKeyId: OSSConfig.accessKeyId,
      accessKeySecret: OSSConfig.accessKeySecret,
      bucket: 'cdzt-test',
      stsToken: OSSConfig.token,
      useFetch: true, // 支持上传大于100KB的文件
      secure:true
    })
    // let data;
    // 创建并填写Blob数据。
    const data = new Blob(['Hello OSS']);
    // 创建并填写OSS Buffer内容。
    // const data = new OSS.Buffer(['Hello OSS']);
    const res = await client.put('exampleobject.txt', file)
    console.log('res' ,res)
    // resolve(res)
    // 或者返回如下：
    // resolve({
    //     fileUrl: `${uploadHost}/${fileName}`,
    //     fileName: file.name
    // })
  })
}

export { uploadOSS }

